package cn.jobstart;

import cn.jobstart.common.*;
import cn.jobstart.common.word.WordUtils;
import cn.jobstart.data.DataUtil;
import cn.jobstart.enums.AdminJobEducationFlagEnum;
import cn.jobstart.enums.CompanyDelFlagEnum;
import cn.jobstart.enums.ResumeBasicDelFlagEnum;
import cn.jobstart.enums.ResumeBasicEducationFlagEnum;
import cn.jobstart.es.listener.ResumeEsListener;
import cn.jobstart.es.listener.event.*;
import cn.jobstart.es.model.ResumeEs;
import cn.jobstart.es.service.ICompanyEsService;
import cn.jobstart.es.service.IResumeEsService;
import cn.jobstart.model.Company;
import cn.jobstart.model.ResumeBasic;
import cn.jobstart.model.ResumeEducationalExperience;
import cn.jobstart.model.ResumeWorkExperience;
import cn.jobstart.modelExt.*;
import cn.jobstart.props.FileConfig;
import cn.jobstart.props.Street;
import cn.jobstart.pubInter.BaseSearch;
import cn.jobstart.pubInter.exception.SkException;
import cn.jobstart.searchExt.*;
import cn.jobstart.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;

/**
 * @author sunke
 * @version 1.0
 * @Description 初始化es
 * @date 2023-09-14 13:28
 */

@Component
@Slf4j
public class InitDataCommand implements CommandLineRunner {


    static int limit = 8000;
    private static final ExecutorService executor = Executors.newScheduledThreadPool(limit);

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    private IResumeBasicService resumeBasicService;
    @Value("${initES}")
    private boolean initES;

    @Resource
    private ICompanyService companyService;

    @Resource
    private ICompanyEsService companyEsService;

    @Resource
    private IResumeWorkExperienceService resumeWorkExperienceService;
    @Resource
    private IResumeEsService resumeEsService;
    @Resource
    private ResumeEsListener resumeEsListener;
    @Resource
    private IPersonService personService;


    @Resource
    private IResumeEducationalExperienceService resumeEducationalExperienceService;


    @Resource
    private DataUtil dataUtil;


    @Resource
    private FileConfig fileConfig;

    private List<Street> streetList;
    @Resource
    private ISchoolService schoolService;
    @Resource
    private IResumeCertificateService resumeCertificateService;

    private void initCityPcasArray() {

        streetList = FileUtil.readInFile(fileConfig.getRoot() + File.separator + "city-pcas.json", Street.class);
        System.out.println(streetList);

    }


    private String modWord(String fileName) {

        final String[] result = {fileName};
        try {

            String fullFilePath = fileConfig.getRoot() + File.separator + fileName;
            String suffix = FileUtil.getSuffix(fullFilePath);
            if (!"docx".equalsIgnoreCase(suffix) && !".doc".equalsIgnoreCase(suffix)) {
                return fileName;
            }


            String targetFilePath = fullFilePath.replace("." + suffix, "_1." + suffix);
            WordUtils.createWord(fullFilePath, new FileOutputStream(targetFilePath), null, SkMap.getInstance(), xwpfTemplate -> {

                List<Integer> removeRowIndex = SkList.getInstance();
                XWPFTable table = null;
                try {

                    table = xwpfTemplate.getXWPFDocument().getTables().get(0);

                    String title = xwpfTemplate.getXWPFDocument().getTables().get(0).getRow(0).getCell(0).getText();
                    if (!"报考信息".equalsIgnoreCase(title)) {
                        return;
                    }

                    removeRowIndex.add(0);

                    List<XWPFTableRow> rows = table.getRows();

                    for (int i = 0; i < rows.size(); i++) {

                        try {

                            String text = rows.get(i).getCell(0).getText().trim();

                            if ("报考考试".equalsIgnoreCase(text) || "报考单位".equalsIgnoreCase(text) || "报考职位".equalsIgnoreCase(text)

                            ) {
                                removeRowIndex.add(i);
                                continue;
                            }


                        } catch (Exception e) {


                        }


                    }


                } catch (Exception e) {

                }
                if (StringUtil.isNotObjEmpty(removeRowIndex) && StringUtil.isNotObjEmpty(table)) {
                    int removeIndex = 0;
                    for (Integer i : removeRowIndex) {
                        table.removeRow(i.intValue() - removeIndex);
                        removeIndex = removeIndex + 1;
                    }


                }

                result[0] = fileName.replace("." + suffix, "_1." + suffix);


            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        }


        return result[0];


    }


    public void updateYYResumeFile() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql("(resume_basic.rb_old_resume_file is not null and resume_basic.rb_old_resume_file!='') and resume_basic.rb_show_flag !=7");
       // search.setCustomSql("rb_id='f62bc738299746ddbd98624ecafc1145'");

        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {
                List<ResumeBasicExt> resultList = resumeBasicService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeBasicExt item : resultList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                     /*   if (!FileUtil.exists(File.separator + item.getOldResumeFile())) {
                            return 1;
                        }*/

                        String result = modWord(item.getOldResumeFile());

                        resumeBasicService.updateDataById(SkMap.getInstance().addObjToMap(ResumeBasic.SHOW_FLAG, 7).addObjToMap(ResumeBasic.OLD_RESUME_FILE, result), item.getId());


                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                resumeBasicService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeBasic.SHOW_FLAG, 7), ResumeBasicSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeBasicExt::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }


    private String getCityByCode(String code) {

        for (Street province : streetList) {
            String provinceName = province.getName();
            String provinceCode = province.getName();

            if (provinceCode.equalsIgnoreCase(code)) {
                return provinceName;
            }

            if (StringUtil.isNotObjEmpty(province.getChildren())) {
                for (Street city : province.getChildren()) {
                    String cityName = city.getName();
                    String cityCode = city.getCode();

                    if (cityCode.equalsIgnoreCase(code)) {
                        return provinceName + "-" + cityName;
                    }


                    if (StringUtil.isNotObjEmpty(city.getChildren())) {
                        for (Street area : city.getChildren()) {
                            String areaName = area.getName();
                            String areaCode = area.getCode();
                            if (areaCode.equalsIgnoreCase(code)) {
                                return provinceName + "-" + cityName + "-" + areaName;
                            }
                            if (StringUtil.isNotObjEmpty(area.getChildren())) {
                                for (Street street : area.getChildren()) {
                                    String streetName = street.getName();
                                    String streetCode = street.getCode();
                                    if (streetCode.equalsIgnoreCase(code)) {
                                        return provinceName + "-" + cityName + "-" + areaName + "-" + streetName;
                                    }

                                }


                            }

                        }

                    }


                }


            }


        }

        return code;

    }

    /**
     * 更新证书时间
     */
    public void updateCertficateTime() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeCertificateSearchExt search = ResumeCertificateSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql(" (resume_certificate.rc_show_flag is null or resume_certificate.rc_show_flag =1)");


        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {

                if (StringUtil.isNullOrEmpty(streetList)) {
                    initCityPcasArray();
                }

                List<ResumeCertificateExt> resultList = resumeCertificateService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeCertificateExt item : resultList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {


                        ResumeCertificateEsUpdateEvent event = new ResumeCertificateEsUpdateEvent();
                        event.setResumeId(item.getResumesId());
                        resumeEsListener.action(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }


                Map<String, Object> dataMap = SkMap.getInstance();
                dataMap.put(ResumeCertificateExt.SHOW_FLAG, 2);
                ResumeCertificateSearchExt idSearch = ResumeCertificateSearchExt.getInstance();
                idSearch.setIdIn(resultList.stream().map(ResumeCertificateExt::getId).collect(Collectors.toList()));
                resumeCertificateService.updateDataBySearch(dataMap, idSearch);

            } catch (Exception e) {

            }


        }


    }


    public void updateLivePlace() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql(" resume_basic.rb_show_flag !=6");


        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {

                if (StringUtil.isNullOrEmpty(streetList)) {
                    initCityPcasArray();
                }

                List<ResumeBasicExt> resultList = resumeBasicService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeBasicExt item : resultList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        String livePlace = item.getLivePlace();
                        String birthPlace = item.getBirthPlace();
                        Map<String, Object> dataMap = SkMap.getInstance();
                        if (NumberUtil.parseInt(livePlace) > 0) {
                            dataMap.put(ResumeBasic.LIVE_PLACE, getCityByCode(livePlace));
                        }
                        if (NumberUtil.parseInt(birthPlace) > 0) {
                            dataMap.put(ResumeBasic.BIRTH_PLACE, getCityByCode(birthPlace));
                        }


                        dataMap.put(ResumeBasic.SHOW_FLAG, 6);


                        resumeBasicService.updateDataById(dataMap, item.getId());


                        ResumeBaseEsUpdateEvent event = new ResumeBaseEsUpdateEvent();
                        event.setResumeId(item.getId());
                        resumeEsListener.action(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                resumeBasicService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeBasic.SHOW_FLAG, 6), ResumeBasicSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeBasicExt::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }

    /**
     * 更新教育经历学校标签
     */
    public void updateEducationSchoolLabel() {


        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeEducationalExperienceSearchExt search = ResumeEducationalExperienceSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql("(resume_educational_experience.ree_show_flag !=2) and (resume_educational_experience.ree_school_label_flag is null or resume_educational_experience.ree_school_label_flag='') and ree_title is not null and ree_title!=''");

        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {
                List<ResumeEducationalExperienceExt> resultList = resumeEducationalExperienceService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeEducationalExperienceExt company : resultList) {


                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        resumeEducationalExperienceService.updateDataById(SkMap.getInstance().addObjToMap(ResumeEducationalExperience.SCHOOL_LABEL_FLAG, dataUtil.getSchoolLabelBySchoolName(company.getTitle())).addObjToMap(ResumeEducationalExperience.SHOW_FLAG, 2), company.getId());

                        ResumeEducationalExperienceUpdateEvent event = new ResumeEducationalExperienceUpdateEvent();
                        event.setResumeId(company.getResumesId());
                        resumeEsListener.action(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                // resumeWorkExperienceService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeWorkExperience.SHOW_FLAG, 2).addObjToMap(ResumeWorkExperience.DEL_FLAG, CompanyDelFlagEnum.N.getType()), ResumeWorkExperienceSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeWorkExperience::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }

    //更新简历基础信息里学历
    public void updateBasicEducation() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql(" (resume_basic.rb_es_flag BETWEEN 0 and 4)");

        int pageSize = limit;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        search.setOrderBy(ResumeBasic.ID);
        search.setOrderDesc(BaseSearch.ASC_ORDER);
        //search.setOrderDesc(BaseSearch.DESC_ORDER);
        while (true) {
            try {
                List<ResumeBasicExt> resultList = resumeBasicService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeBasicExt resume : resultList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        String resumeId = resume.getId();
                        try {


                            Map<String, Object> dataMap = SkMap.getInstance();


                            dataMap.put(ResumeBasic.ES_FLAG, 5);


                            resumeBasicService.updateDataById(dataMap, resume.getId());
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        try {
                            ResumeEs resumeEs = resumeEsService.detailById(resume.getId());
                            BeanUtils.copyPropertiesIgnoreNull(resume, resumeEs);
                            resumeEs.setEducationFlag(ResumeBasicEducationFlagEnum.getDescByType(resume.getEducation()));
                            resumeEs.setEducation(resume.getEducation());

                            resumeEs.setId(resumeId);
                            resumeEs.setThirdAccountId(resume.getKzpStudentId());
                            resumeEsService.update(resumeEs, resumeEs.getId());

                            return 1;
                        }catch (Exception e){
                            e.printStackTrace();

                        }
                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

//                resumeBasicService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeBasic.SHOW_FLAG, 5).addObjToMap(ResumeBasic.DEL_FLAG, CompanyDelFlagEnum.N.getType()), ResumeBasicSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeBasicExt::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }

    /**
     * 更新教育经历的学校
     */

    public void updateEducationSchool() {
        List<SchoolExt> schoolList = null;
        try {
            schoolList = schoolService.getAllList(null);
        } catch (SkException e) {

        }
        if (StringUtil.isNullOrEmpty(schoolList)) {
            return;
        }


        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeEducationalExperienceSearchExt search = ResumeEducationalExperienceSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql(" resume_educational_experience.ree_show_flag!=4 and (resume_educational_experience.ree_title is null or resume_educational_experience.ree_title='') and ree_detail is not null and ree_detail!=''");

        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {
                List<ResumeEducationalExperienceExt> resultList = resumeEducationalExperienceService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeEducationalExperienceExt company : resultList) {

                    List<SchoolExt> finalSchoolList = schoolList;

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        String schoolName = "";
                        for (SchoolExt school : finalSchoolList) {
                            if (company.getDetail().indexOf(school.getName()) >= 0) {
                                schoolName = school.getName();
                                break;
                            }

                        }

                        Map<String, Object> dataMap = SkMap.getInstance();
                        if (StringUtil.isNotObjEmpty(schoolName)) {
                            dataMap.put(ResumeEducationalExperience.TITLE, schoolName);
                        }
                        dataMap.put(ResumeEducationalExperience.SHOW_FLAG, 4);

                        resumeEducationalExperienceService.updateDataById(dataMap, company.getId());

                        ResumeEducationalExperienceUpdateEvent event = new ResumeEducationalExperienceUpdateEvent();
                        event.setResumeId(company.getResumesId());
                        resumeEsListener.action(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                // resumeWorkExperienceService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeWorkExperience.SHOW_FLAG, 2).addObjToMap(ResumeWorkExperience.DEL_FLAG, CompanyDelFlagEnum.N.getType()), ResumeWorkExperienceSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeWorkExperience::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }

    //更新学历
    public void updateEducation() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeEducationalExperienceSearchExt search = ResumeEducationalExperienceSearchExt.getInstance();
        search.setDelFlagEq(null);

        search.setCustomSql("resume_educational_experience.ree_show_flag!=10 and (resume_educational_experience.ree_unit_type is null or resume_educational_experience.ree_unit_type='') and ree_detail is not null and ree_detail!=''");

        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {
                List<ResumeEducationalExperienceExt> resultList = resumeEducationalExperienceService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeEducationalExperienceExt company : resultList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        Map<String, Object> dataMap = SkMap.getInstance();
                        dataMap.put(ResumeEducationalExperience.UNIT_TYPE, AdminJobEducationFlagEnum.matching(company.getDetail()));
                        dataMap.put(ResumeEducationalExperience.SHOW_FLAG, 10);

                        resumeEducationalExperienceService.updateDataById(dataMap, company.getId());

                        ResumeEducationalExperienceUpdateEvent event = new ResumeEducationalExperienceUpdateEvent();
                        event.setResumeId(company.getResumesId());

                        resumeEsListener.action(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                // resumeWorkExperienceService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeWorkExperience.SHOW_FLAG, 2).addObjToMap(ResumeWorkExperience.DEL_FLAG, CompanyDelFlagEnum.N.getType()), ResumeWorkExperienceSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeWorkExperience::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }


    //更新工作经历到es
    public void updateWorkEs() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        ResumeWorkExperienceSearchExt search = ResumeWorkExperienceSearchExt.getInstance();
        search.setDelFlagEq(null);
        search.setCustomSql("(resume_work_experience.rwe_show_flag is null or resume_work_experience.rwe_show_flag=1)");
        // search.setEsFlagIn(SkList.getInstance().addObjToList(CompanyEsFlagEnum.N.getType().intValue()));
        //  search.setNotInField(Company.ES_FLAG,SkList.getInstance().addObjToList(CompanyEsFlagEnum.Y.getType().intValue()));
        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {
                List<ResumeWorkExperienceExt> resultList = resumeWorkExperienceService.getList(search);
                if (StringUtil.isNullOrEmpty(resultList)) {
                    break;
                }

                for (ResumeWorkExperienceExt company : resultList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        ResumeWorkExperienceEsUpdateEvent event = new ResumeWorkExperienceEsUpdateEvent();
                        event.setResumeId(company.getResumesId());

                        resumeEsListener.action(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                resumeWorkExperienceService.updateDataBySearch(SkMap.getInstance().addObjToMap(ResumeWorkExperience.SHOW_FLAG, 2).addObjToMap(ResumeWorkExperience.DEL_FLAG, CompanyDelFlagEnum.N.getType()), ResumeWorkExperienceSearchExt.getInstance().setIdIn(resultList.stream().map(ResumeWorkExperience::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }

    public void initCompanyEs() {

        List<FutureTask<Integer>> futureList = new ArrayList<>();

        CompanySearchExt search = CompanySearchExt.getInstance();
        search.setDelFlagEq(null);
        search.setCustomSql("(company.c_es_flag is null or company.c_es_flag=0 or company.c_es_flag=1)");
        // search.setEsFlagIn(SkList.getInstance().addObjToList(CompanyEsFlagEnum.N.getType().intValue()));
        //  search.setNotInField(Company.ES_FLAG,SkList.getInstance().addObjToList(CompanyEsFlagEnum.Y.getType().intValue()));
        int pageSize = limit / 2;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {
            try {
                List<CompanyExt> companyList = companyService.getList(search);
                if (StringUtil.isNullOrEmpty(companyList)) {
                    break;
                }

                for (CompanyExt company : companyList) {

                    FutureTask<Integer> futureTask = new FutureTask<>(() -> {

                        CompanyEsEvent event = new CompanyEsEvent();
                        event.setCompanyId(company.getId());
                        event.setType(0);
                        companyEsService.publishEvent(event);

                        return 1;

                    });

                    futureList.add(futureTask);
                    executor.submit(futureTask);

                }

                Thread.sleep(1000);

                for (FutureTask task : futureList) {
                    try {
                        task.get();
                    } catch (Exception e) {

                    }
                }

                companyService.updateDataBySearch(SkMap.getInstance().addObjToMap(Company.ES_FLAG, 2).addObjToMap(Company.DEL_FLAG, CompanyDelFlagEnum.N.getType())


                        , CompanySearchExt.getInstance().setIdIn(companyList.stream().map(Company::getId).collect(Collectors.toList())));

            } catch (Exception e) {

            }


        }


    }

    public void updatePersonId() {

        List<FutureTask<String>> futureList = new ArrayList<>();

        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();

        // search.setEsFlagIn(SkList.getInstance().addObjToList(ResumeBasicEsFlagEnum.N.getType().intValue()));
        // search.setNotInField(ResumeBasic.ES_FLAG,SkList.getInstance().addObjToList(ResumeBasicEsFlagEnum.Y.getType().intValue()));
        // search.setCustomSql("(resume_basic.rb_es_flag is null or resume_basic.rb_es_flag=0)");
        search.setCustomSql(" resume_basic.rb_person_id=1");
        //  search.setIdIn(SkList.getInstance().addObjToList("405e0cbbcc7e4b1b9af68b8f12798c64"));
        int pageSize = limit;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);

        while (true) {

            try {
                List<String> resumeIdList = resumeBasicService.getIdListBySearch(search);
                if (StringUtil.isNullOrEmpty(resumeIdList)) {
                    break;
                }

                for (String id : resumeIdList) {

                    FutureTask<String> futureTask = new FutureTask<String>(() -> {


                        ResumeBasicExt resumeBasic = resumeBasicService.getDetail(id, new HashSet<>());


                        PersonExt person = new PersonExt();
                        person.setId(IdGen.uuid());
                        person.setTruename(resumeBasic.getTruename());
                        person.setPhone(resumeBasic.getMobile());
                        person.setIdcard(resumeBasic.getIdcard());
                        String personId = person.getId();
                        personService.insert(person);


                        ResumeEs resumeEs = resumeEsService.detailById(id);
                        resumeEs.setId(id);
                        resumeEs.setPersonId(personId);
                        resumeEsService.update(resumeEs, resumeEs.getId());

                        resumeBasicService.updateDataById(SkMap.getInstance().addObjToMap(ResumeBasic.PERSON_ID, personId), id);


                        return id;

                    });


                    futureList.add(futureTask);
                    executor.submit(futureTask);


                }
                Thread.sleep(1000);

                //等所有的都结果
                futureList.stream().forEach(task -> {
                    try {
                        String resumeId = task.get();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });

                futureList.clear();


            } catch (Exception e) {

            }


        }


    }

    public void initResumeEs() {

        List<FutureTask<String>> futureList = new ArrayList<>();

        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();

        // search.setEsFlagIn(SkList.getInstance().addObjToList(ResumeBasicEsFlagEnum.N.getType().intValue()));
        // search.setNotInField(ResumeBasic.ES_FLAG,SkList.getInstance().addObjToList(ResumeBasicEsFlagEnum.Y.getType().intValue()));
        // search.setCustomSql("(resume_basic.rb_es_flag is null or resume_basic.rb_es_flag=0)");
        search.setCustomSql(" resume_basic.rb_es_flag BETWEEN 0 and 3");
        //  search.setIdIn(SkList.getInstance().addObjToList("405e0cbbcc7e4b1b9af68b8f12798c64"));
        int pageSize = limit;
        search.setPageSize(pageSize);
        search.setPageNumber(1);
        search.setDelFlagEq(null);
        // search.setOrderBy("RAND()");

        search.setOrderBy(ResumeBasic.ID);
        search.setOrderDesc(BaseSearch.DESC_ORDER);
      /*  search.setOrderBy(ResumeBasic.CREATE_TIME);
        search.setOrderDesc(BaseSearch.DESC_ORDER);

        search.setOrderBy(ResumeBasic.CREATE_TIME);
        search.setOrderDesc(BaseSearch.ASC_ORDER);
*/

        while (true) {

            try {
                List<String> resumeIdList = resumeBasicService.getIdListBySearch(search);
                if (StringUtil.isNullOrEmpty(resumeIdList)) {
                    break;
                }

                for (String id : resumeIdList) {

                    FutureTask<String> futureTask = new FutureTask<String>(() -> {

                        try {
                            resumeEsListener.baseAddAll(id);


                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                        resumeBasicService.updateDataById(SkMap.getInstance().addObjToMap(ResumeBasic.ES_FLAG, 4).addObjToMap(ResumeBasic.DEL_FLAG, ResumeBasicDelFlagEnum.N.getType()), id);

                        ///   applicationEventPublisher.publishEvent(resumeEsEvent);

                        return id;

                    });


                    futureList.add(futureTask);
                    executor.submit(futureTask);


                }
                Thread.sleep(1000);

                //等所有的都结果
                futureList.stream().forEach(task -> {
                    try {
                        String resumeId = task.get();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });

                futureList.clear();


            } catch (Exception e) {

            }


        }


    }


    /*  *//**
     * 初始化简历
     *//*
    public void doRunResumeEs() {


        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();
        search.setEsFlagIn(SkList.getInstance().addObjToList(ResumeBasicEsFlagEnum.N.getType().intValue()));
        int pageNum = 1;
        int pageSize = 1000;
        search.setPageSize(pageSize);
        search.setDelFlagEq(null);
        while (true) {

            try {

                List<String> list = null;

                list = resumeBasicService.getIdListBySearch(search);
                if (StringUtil.isNullOrEmpty(list)) {
                    break;
                }


                list.stream().forEach(id -> {


                    ResumeEsEvent resumeEsEvent = new ResumeBaseEsAddAllEvent();
                    resumeEsEvent.setResumeId(id);

                    applicationEventPublisher.publishEvent(resumeEsEvent);


                    try {
                        //防上还有发布消息，又重新发布
                        resumeBasicService.updateDataById(SkMap.getInstance().addObjToMap(ResumeBasic.ES_FLAG, ResumeBasicEsFlagEnum.Y.getType()), id);
                    } catch (SkException e) {

                    }

                });

            } catch (Exception e) {

            }


        }


    }*/


    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        if (initES) {


            new Thread(new Runnable() {
                @Override
                public void run() {
                    updateBasicEducation();
                }
            }).start();


        /*    new Thread(new Runnable() {
                @Override
                public void run() {
                    updateYYResumeFile();
                }
            }).start();*/

          /*  new Thread(new Runnable() {
                @Override
                public void run() {
                    updateCertficateTime();
                }
            }).start();
*/



          /*  new Thread(new Runnable() {
                @Override
                public void run() {
                    updateLivePlace();
                }
            }).start();*/

            //    initResumeEs();

            //initCompanyEs()

           /* new Thread(new Runnable() {
                @Override
                public void run() {
                    updateWorkEs();
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    updateEducation();
                }
            }).start();


            new Thread(new Runnable() {
                @Override
                public void run() {
                    updateBasicEducation();
                }
            }).start();


            new Thread(new Runnable() {
                @Override
                public void run() {
                    updateEducationSchool();
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    updateEducationSchoolLabel();
                }
            }).start();*/


        }
    }
}
